import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';
import { authService } from '../services/authService';

interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

export default function Login() {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { login } = useAuthStore();

  const onFinish = async (values: LoginForm) => {
    setLoading(true);
    try {
      const response = await authService.login({
        username: values.username,
        password: values.password,
        rememberMe: values.remember
      });

      // 检查响应是否成功
      if (response && response.token && response.user) {
        // 调用store的login方法更新认证状态
        login(response.user, response.token);
        
        // 如果选择记住密码，保存到localStorage
        if (values.remember) {
          localStorage.setItem('rememberedUsername', values.username);
        } else {
          localStorage.removeItem('rememberedUsername');
        }
        
        message.success('登录成功');
        navigate('/dashboard');
      } else {
        message.error('登录失败：服务器响应异常');
      }
    } catch (error: any) {
      console.error('登录错误:', error);
      
      // 处理不同的错误状态码
      if (error.response) {
        const { status, data } = error.response;
        switch (status) {
          case 401:
            message.error(data?.message || '用户名或密码错误');
            break;
          case 403:
            message.error('账户已被禁用，请联系管理员');
            break;
          case 429:
            message.error('登录尝试过于频繁，请稍后再试');
            break;
          case 500:
            message.error('服务器内部错误，请稍后再试');
            break;
          default:
            message.error(data?.message || '登录失败，请检查网络连接');
        }
      } else if (error.request) {
        message.error('网络连接失败，请检查网络设置');
      } else {
        message.error('登录失败，请稍后再试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 获取记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername') || '';

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl mb-4">
            <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
          </div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">UniFlow</h1>
          <p className="text-gray-600">统一工作流与数据智能平台</p>
        </div>

        {/* 登录表单 */}
        <Card className="shadow-xl border-0 rounded-2xl">
          <div className="p-6">
            <h2 className="text-2xl font-semibold text-center text-gray-800 mb-6">欢迎登录</h2>
            
            <Form
              name="login"
              initialValues={{ 
                remember: true,
                username: rememberedUsername
              }}
              onFinish={onFinish}
              size="large"
              layout="vertical"
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' }
                ]}
              >
                <Input
                  prefix={<UserOutlined className="text-gray-400" />}
                  placeholder="请输入用户名"
                  className="rounded-lg"
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' }
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="text-gray-400" />}
                  placeholder="请输入密码"
                  className="rounded-lg"
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>

              <Form.Item>
                <div className="flex items-center justify-between">
                  <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox>记住用户名</Checkbox>
                  </Form.Item>
                  <a className="text-blue-600 hover:text-blue-800 text-sm" href="#">
                    忘记密码？
                  </a>
                </div>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  className="w-full h-12 rounded-lg bg-gradient-to-r from-blue-600 to-purple-600 border-0 text-white font-medium hover:from-blue-700 hover:to-purple-700"
                >
                  {loading ? '登录中...' : '登录'}
                </Button>
              </Form.Item>
            </Form>

            {/* 快速登录提示 */}
            <div className="mt-6 p-4 bg-blue-50 rounded-lg">
              <p className="text-sm text-blue-800 text-center mb-2">
                <strong>演示账号</strong>
              </p>
              <div className="text-xs text-blue-600 space-y-1">
                <div>管理员: admin / 123456</div>
                <div>普通用户: user / 123456</div>
              </div>
            </div>
          </div>
        </Card>

        {/* 底部信息 */}
        <div className="text-center mt-8 text-sm text-gray-500">
          <p>&copy; 2024 UniFlow Platform. All rights reserved.</p>
        </div>
      </div>
    </div>
  );
}